package com.iheart.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

public class Sha {
	public String exec(String stringKey) {
		System.out.println("stringKey : " + stringKey);
		String resultKeySet="",bf="";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
			String shaString = stringKey;
			byte[] byteTemp = shaString.getBytes();
            md.update(byteTemp);
            byte[] raw = md.digest();
            

			for (int i=0;i<raw.length;i++) {
				String tmp = "0"+Integer.toHexString(raw[i]);
				tmp = tmp.substring(tmp.length()-2);
				bf+=tmp;
			}
			//System.out.println(bf);
			resultKeySet=bf;
        } catch(NoSuchAlgorithmException nalgoe) {
            System.err.println(nalgoe);
        }
		return resultKeySet;
    }
     //public static void main(String[] args) {
     //   MasherMain masher = new MasherMain();
     //   String rkey=masher.exec("test123","TEST123","20070506","TEST123");
	//	String webroid = masher.decodeWebroId(rkey);
	//	System.out.println(webroid);
    //}

	public String decodeWebroId(String rKey) {
		System.out.println(rKey);
		String Webroid="";
		try
		{	
			String idTemp = rKey.substring(40,rKey.length());
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] raw = decoder.decodeBuffer(idTemp);
			Webroid=new String(raw);	
		}
		catch (Exception e)
		{
			System.out.println(e.toString());
		}
		return Webroid;
	}

	public String encodePacket(String certKey) {
		String returnKey="";
		try
		{	
			BASE64Encoder encoder = new BASE64Encoder();
            returnKey = encoder.encode(certKey.getBytes());	
		}
		catch (Exception e)
		{
			System.out.println(e.toString());
		}
		return returnKey;
	}
	
	public String decodePacket(String certKey) {
		String returnKey="";
		try
		{	
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] raw = decoder.decodeBuffer(certKey);
			returnKey=new String(raw);
		}
		catch (Exception e)
		{
			System.out.println(e.toString());
		}
		return returnKey;
	}
}
